package cn.wolfcode.mq;

import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.service.IOrderInfoService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * @ClassName OrderTXMsgListener
 * @Author VCR
 * @Date 2022/1/6 20:48
 * @Version 1.0
 */
@Component
@RocketMQTransactionListener(txProducerGroup = "tx_group")
@Slf4j
public class OrderTXMsgListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * // 执行本地事务方法
     * @param message 消息内容
     * @param object  订单编号
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object object) {
        log.info("执行本地事务");
        String orderNo = (String) object;
        try {
            orderInfoService.executeLocalTransaction(orderNo);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }


    // 检查本地事务方法
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查本地事务");
        // 看订单状态
        String objJson = new String((byte[]) message.getPayload());
        OperateIntergralVo operateIntergralVo = JSON.parseObject(objJson, OperateIntergralVo.class);
        OrderInfo orderInfo = orderInfoMapper.select(operateIntergralVo.getPk());
        if (orderInfo.getStatus().equals(OrderInfo.STATUS_REFUND)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
